package service

import (
	"context"
	"errors"
	"time"
	"user-center/model"
	"user-center/pool"
	_ "user-center/userINF"
)

type userService struct{}

/*
UserRegister
用户注册
*/
func (u *userService) UserRegister(user *model.User) error {
	db := pool.GetDB()
	var userCount int64
	db.Model(user).Where("userAccount", user.UserAccount).Count(&userCount)
	//数量大于0 该用户已经存在，不给予注册
	if userCount > 0 {
		return errors.New("user already exists")
	}
	user.UserAuth = 0
	user.UserSex = 0
	user.CreateTime = time.Now()
	user.UpdateTime = time.Now()
	db.Create(&user)
	return nil
}

var ctx = context.Background()

/*
UserLogin
用户登陆
*/
func (u *userService) UserLogin(user *model.User) error {
	db := pool.GetDB()
	var queryUser model.User
	db.Where("userAccount", user.UserAccount).First(&queryUser)
	if queryUser.UserPassword != user.UserPassword {
		return errors.New("user password error")
	}
	//登陆的时候存储用户session
	rdb := pool.GetRedis()
	err := rdb.Set(ctx, model.UserLoginState, queryUser.Id, 12*time.Hour).Err()
	if err != nil {
		return errors.New("redis set session error")
	}
	return nil
}

/*
UserLogout
用户退出
*/
func (u *userService) UserLogout() error {
	rdb := pool.GetRedis()
	err := rdb.Del(ctx, model.UserLoginState)
	if err != nil {
		return errors.New("redis del session error")
	}
	return nil
}

/*
GetLoginUser
获得当前登陆用户
*/
func (u *userService) GetLoginUser() (model.User, error) {
	rdb := pool.GetRedis()
	loginId := rdb.Get(ctx, model.UserLoginState)
	db := pool.GetDB()
	loginUser := model.User{}
	err := db.First(&loginUser, "id = ?", loginId)
	if err != nil {
		return model.User{}, errors.New("user not found")
	}
	return loginUser, nil
}
